package com.lfg.leetcode.leetcode100;


import java.util.HashMap;
import java.util.Map;

public class No138copyRandomList {

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node5 = new Node(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node5;
        node1.random = node3;
        node3.random = node5;
        node5.random = node1;
        Node node = copyRandomList(node1);
        System.out.println(node);
    }

    public static Node copyRandomList(Node head) {
        if (null == head) {
            return null;
        }
        Map<Node, Node> newMap = new HashMap<>(64);
        Node ret = null;
        Node node = head;
        while (node != null) {
            Node value = new Node(node.val);
            newMap.put(node, value);
            node = node.next;
        }
        node = head;
        Node last = null;
        while (node != null) {
            Node value = newMap.get(node);
            if (ret == null) {
                ret = value;
            } else {
                last.next = value;
            }

            if (node.random != null) {
                value.random = newMap.get(node.random);
            }
            last = value;
            node = node.next;
        }

        return ret;

    }

    public static Node copyRandomList(Node head, Map<Integer, Node> map) {
        if (null == head) {
            return null;
        }
        Node node = map.get(head.val);
        if (null != node) {
            return node;
        }
        node = map.computeIfAbsent(head.val, key -> new Node(head.val));
        node.next = copyRandomList(head.next, map);
        node.random = copyRandomList(head.random, map);

        return node;
    }
}
